Closures in Lua

An inner function can retain access to local variables from its enclosing scope. The retained external local variable is called an upvalue. The function, together with its captured upvalues forms a closure.

local function make_counter()
    local count = 0

    return function()
        count = count + 1
        return count
    end
end

local counter = make_counter()

print(counter())  -- 1
print(counter())  -- 2
print(counter())  -- 3

Date: 2026-07-24 Fri